package com.soft.service;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.soft.entity.Class;
import com.soft.entity.Student;
import com.soft.mapper.ClassMapper;
import com.soft.mapper.StudentMapper;

@Service
public class ClassService {
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private StudentMapper studentMapper;

    // 查询所有班级
    public List<Class> queryAll() {
        return classMapper.selectList(null);
    }

    // 插入新班级
    public int insert(String name, String num, String departmentId) {
        Class clazz = new Class();
        clazz.setName(name);
        clazz.setNum(num);
        clazz.setDepartmentId(departmentId);
        return classMapper.insert(clazz);
    }

    // 根据ID更新班级信息
    public int updateNumById(String id, String num) {
        UpdateWrapper<Class> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id).set("num", num);
        return classMapper.update(null, wrapper);
    }

    // 根据ID删除班级
    public int deleteById(String id) {
        return classMapper.deleteById(id);
    }
    //根据某个班级的名字，搜索出其所属系的所有学生
    public List<Student> getStudentsByClassName(String className) {
        // 1. 查出该班级
        QueryWrapper<Class> classWrapper = new QueryWrapper<>();
        classWrapper.eq("name", className);
        Class clazz = classMapper.selectOne(classWrapper);
        if (clazz == null) {
            return null;
        }

        // 2. 查出同系所有班级id
        QueryWrapper<Class> deptClassWrapper = new QueryWrapper<>();
        deptClassWrapper.eq("department_id", clazz.getDepartmentId());
        List<Class> deptClasses = classMapper.selectList(deptClassWrapper);
        List<String> classIds = deptClasses.stream().map(Class::getId).collect(Collectors.toList());

        // 3. 查出所有 class_id 属于这些班级的学生
        if (classIds.isEmpty()) {
            return null;
        }
        QueryWrapper<Student> studentWrapper = new QueryWrapper<>();
        studentWrapper.in("class_id", classIds);
        return studentMapper.selectList(studentWrapper);
    }
    
}